package com.company.config.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.lang.reflect.Method;

/**
* @author jiayazi
* @Title: RedisCacheConfig
* @ProjectName smart-planet
* @Description:
 * 1、通过继承CachingConfigurerSupport，将Spring-Cache的缓存换为Redis
 * 2、使用适合项目的key生成策略cacheKeyGenerator
* @date 2018/11/1下午5:53
*/
@Configuration
@EnableCaching // 缓存注解
@ConditionalOnExpression(value = "${planet.cache.redis.open}")
public class RedisCacheConfig extends CachingConfigurerSupport {
   private static final Logger LOGGER = LoggerFactory.getLogger(RedisCacheConfig.class);

   @Bean
   public CacheManager cacheManager(RedisConnectionFactory factory) {
       LOGGER.info("配 置 redis 缓 存, 缓 存 参 数 planet.cache.redis.open : true");
       RedisCacheManager cacheManager = RedisCacheManager.create(factory);
       return cacheManager;
   }

   @Bean
   public KeyGenerator customKeyGenerator() {
       return new KeyGenerator() {
           public Object generate(Object o, Method method, Object... objects) {
               StringBuilder sb = new StringBuilder();
               sb.append(o.getClass().getName());
               sb.append(method.getName());
               for (Object obj : objects) {
                   sb.append(obj.toString());
               }
               return sb.toString();
           }
       };
   }


}
